package priv.tuyou.exception.advive;

import java.io.PrintWriter;
import java.lang.reflect.Method;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import priv.tuyou.bo.AppData;
import priv.tuyou.constants.WebContext;

import com.alibaba.fastjson.JSON;

/**
 * 前段请求异常处理，动态判断是返回json还是html
 * @author：涂有
 * @date 2016年12月20日 下午10:38:32
 */
@ControllerAdvice
public class ControllerExceptionAdvice {

	@ExceptionHandler
	public String exceptionHanlder(Exception ex, PrintWriter pw) throws ClassNotFoundException{
		
		StackTraceElement[] stack = ex.getStackTrace();
		for(StackTraceElement element : stack){
			
			Class<?> cla = Class.forName(element.getClassName());
			Controller controller = cla.getAnnotation(Controller.class);
			if(controller != null){
				
				Method[] methods = cla.getMethods();
				for(Method method : methods){
					
					if(element.getMethodName().equals(method.getName())){
						
						ResponseBody responseBody = (ResponseBody)method.getAnnotation(ResponseBody.class);
						if(responseBody != null){ //返回json
							
							pw.println(JSON.toJSON(new AppData(0, ex.getMessage(), null)).toString());
							return null;
						}else{ //返回html
							
							WebContext.getRequest().setAttribute("exception", ex);
							return "forward:WEB-INF/jsp/manager/common/5xx.jsp";
						}
					}
				}
			}
		}
		pw.println(JSON.toJSON(new AppData(0, ex.getMessage(), null)).toString());
		return null;
	}
}
